"""
WVP集成API端点
WVP Integration API Endpoints
"""
import logging
from datetime import datetime
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel

from api.services import WVPDeviceService, WVPChannelService

logger = logging.getLogger(__name__)
router = APIRouter()

# 创建服务实例
wvp_device_service = WVPDeviceService()
wvp_channel_service = WVPChannelService()


class DeviceRegister(BaseModel):
    """设备注册请求模型"""
    device_id: str
    device_name: str
    device_type: str = "camera"
    manufacturer: Optional[str] = None
    model: Optional[str] = None
    ip_address: Optional[str] = None
    port: int = 5060
    username: Optional[str] = None
    password: Optional[str] = None


@router.get("/devices", response_model=List[Dict[str, Any]])
async def get_wvp_devices(
    status: Optional[str] = Query(None, description="按状态筛选"),
    online: Optional[bool] = Query(None, description="按在线状态筛选"),
    limit: int = Query(100, ge=1, le=1000, description="返回数量限制")
):
    """获取WVP设备列表"""
    try:
        devices = await wvp_device_service.get_devices(
            status=status,
            online=online,
            limit=limit
        )
        return devices
    except Exception as e:
        logger.error(f"获取WVP设备列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取WVP设备列表失败")


@router.get("/devices/{device_id}", response_model=Dict[str, Any])
async def get_wvp_device(device_id: str):
    """获取单个WVP设备信息"""
    try:
        device = await wvp_device_service.get_device(device_id)
        if not device:
            raise HTTPException(status_code=404, detail="WVP设备不存在")
        return device
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取WVP设备信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取WVP设备信息失败")


@router.post("/devices/register", response_model=Dict[str, Any])
async def register_wvp_device(device_data: DeviceRegister):
    """注册WVP设备"""
    try:
        device_id = await wvp_device_service.register_device(device_data.dict())
        if not device_id:
            raise HTTPException(status_code=400, detail="注册WVP设备失败")
        
        # 返回注册的设备信息
        device = await wvp_device_service.get_device(device_data.device_id)
        return device
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"注册WVP设备失败: {e}")
        raise HTTPException(status_code=500, detail="注册WVP设备失败")


@router.delete("/devices/{device_id}")
async def unregister_wvp_device(device_id: str):
    """注销WVP设备"""
    try:
        # 检查设备是否存在
        existing_device = await wvp_device_service.get_device(device_id)
        if not existing_device:
            raise HTTPException(status_code=404, detail="WVP设备不存在")
        
        success = await wvp_device_service.unregister_device(device_id)
        if not success:
            raise HTTPException(status_code=400, detail="注销WVP设备失败")
        
        return {"message": "WVP设备注销成功", "device_id": device_id}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"注销WVP设备失败: {e}")
        raise HTTPException(status_code=500, detail="注销WVP设备失败")


@router.get("/devices/{device_id}/channels", response_model=List[Dict[str, Any]])
async def get_device_channels(device_id: str):
    """获取设备通道列表"""
    try:
        # 检查设备是否存在
        existing_device = await wvp_device_service.get_device(device_id)
        if not existing_device:
            raise HTTPException(status_code=404, detail="WVP设备不存在")
        
        channels = await wvp_channel_service.get_device_channels(device_id)
        return channels
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取设备通道列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取设备通道列表失败")


@router.get("/channels/{channel_id}/play-url")
async def get_channel_play_url(channel_id: str):
    """获取通道播放地址"""
    try:
        # 使用服务层方法获取播放地址
        play_info = await wvp_channel_service.get_play_url(channel_id)
        if not play_info:
            raise HTTPException(status_code=404, detail="通道不存在或无法获取播放地址")
        
        return play_info
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取播放地址失败: {e}")
        raise HTTPException(status_code=500, detail="获取播放地址失败")


@router.post("/sync/devices")
async def sync_wvp_devices():
    """从Java后端同步WVP设备和通道数据到本地数据库"""
    try:
        from sync_real_wvp_data import sync_real_wvp_data
        
        logger.info("🔄 开始从Java后端同步WVP数据...")
        
        # 调用真实的WVP数据同步函数
        result = await sync_real_wvp_data()
        
        if result and result.get("success"):
            return {
                "success": True,
                "message": "WVP数据同步完成",
                "synced_devices": result.get("synced_devices", 0),
                "synced_channels": result.get("synced_channels", 0),
                "converted_cameras": result.get("converted_cameras", 0),
                "total_cameras": result.get("total_cameras", 0),
                "wvp_cameras": result.get("wvp_cameras", 0),
                "sync_time": datetime.now().isoformat()
            }
        else:
            error_msg = result.get('error') if result else "同步失败"
            logger.error(f"WVP数据同步失败: {error_msg}")
            raise HTTPException(status_code=500, detail=f"WVP数据同步失败: {error_msg}")
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"同步WVP设备失败: {e}")
        raise HTTPException(status_code=500, detail=f"同步WVP设备失败: {str(e)}")


@router.post("/sync-and-convert")
async def sync_and_convert_wvp():
    """一键同步WVP数据并转换为摄像头"""
    try:
        logger.info("🚀 开始一键同步和转换WVP数据...")
        
        # 1. 先同步数据
        sync_result = await sync_wvp_devices()
        
        if not sync_result.get("success"):
            raise HTTPException(status_code=500, detail="数据同步失败")
        
        logger.info("✅ 数据同步完成，开始转换摄像头...")
        
        # 2. 再转换摄像头
        convert_result = await convert_wvp_to_cameras()
        
        if not convert_result.get("success"):
            raise HTTPException(status_code=500, detail="摄像头转换失败")
        
        logger.info("🎉 一键同步和转换完成!")
        
        return {
            "success": True,
            "message": "WVP数据同步和转换完成",
            "sync_result": sync_result,
            "convert_result": convert_result,
            "total_time": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"一键同步和转换失败: {e}")
        raise HTTPException(status_code=500, detail=f"一键同步和转换失败: {str(e)}")


@router.post("/convert-to-cameras")
async def convert_wvp_to_cameras():
    """将WVP设备转换为摄像头 - 优先从Java后端读取，降级到本地数据"""
    try:
        from api.services import CameraService
        from sync_real_wvp_data import RealWVPClient
        
        camera_service = CameraService()
        converted_count = 0
        skipped_count = 0
        error_count = 0
        
        logger.info("🚀 开始WVP设备转换为摄像头...")
        
        # Java后端WVP服务地址
        wvp_urls = [
            "http://localhost:18080",  # 默认WVP端口
            "http://localhost:8080",   # 备用端口
            "http://127.0.0.1:18080",
            "http://127.0.0.1:8080"
        ]
        
        # 尝试连接WVP服务
        devices = []
        connected_url = None
        use_local_data = False
        
        for wvp_url in wvp_urls:
            logger.info(f"🔌 尝试连接WVP服务: {wvp_url}")
            try:
                async with RealWVPClient(wvp_url) as client:
                    if await client.test_connection():
                        devices = await client.get_devices()
                        if devices:
                            connected_url = wvp_url
                            logger.info(f"✅ 成功从WVP服务 {wvp_url} 获取到 {len(devices)} 个设备")
                            break
            except Exception as e:
                logger.debug(f"连接 {wvp_url} 失败: {e}")
                continue
        
        # 如果无法从Java后端获取数据，使用本地数据
        if not devices:
            logger.warning("⚠️ 无法从Java后端获取WVP数据，使用本地数据库数据")
            use_local_data = True
            
            # 从本地数据库获取WVP设备
            local_devices = await wvp_device_service.get_devices()
            if not local_devices:
                raise HTTPException(
                    status_code=404, 
                    detail="WVP Java后端没有设备数据，本地数据库也没有WVP设备。请检查WVP系统中是否有注册的设备"
                )
            
            # 转换本地设备格式
            devices = []
            for device in local_devices:
                devices.append({
                    "deviceId": device.get("device_id"),
                    "name": device.get("device_name"),
                    "ip": device.get("ip"),
                    "port": device.get("port", 5060),
                    "online": device.get("status") == "online"
                })
            
            logger.info(f"📊 从本地数据库获取到 {len(devices)} 个WVP设备")
        
        # 重新建立连接进行数据转换
        async with RealWVPClient(connected_url) as client:
            
            # 1. 从Java后端获取设备列表
            logger.info("📡 从Java后端获取WVP设备列表...")
            devices = await client.get_devices()
            
            if not devices:
                logger.warning("⚠️ Java后端没有返回WVP设备数据")
                raise HTTPException(
                    status_code=404, 
                    detail="WVP Java后端没有设备数据。请检查WVP系统中是否有注册的设备"
                )
            
            logger.info(f"📊 从Java后端获取到 {len(devices)} 个WVP设备")
            
            # 2. 处理每个设备
            for device in devices:
                device_id = device.get("deviceId") or device.get("id") or device.get("device_id")
                if not device_id:
                    logger.warning(f"⚠️ 设备缺少ID，跳过: {device}")
                    error_count += 1
                    continue
                
                device_name = (device.get("name") or 
                             device.get("deviceName") or 
                             device.get("device_name") or 
                             f"设备-{device_id}")
                
                logger.info(f"🔧 处理设备: {device_id} ({device_name})")
                
                try:
                    # 3. 从Java后端获取设备通道
                    channels = await client.get_device_channels(device_id)
                    
                    if not channels:
                        # 如果没有通道，创建一个默认通道
                        logger.info(f"  设备 {device_id} 没有通道，创建默认摄像头")
                        channels = [{
                            "channelId": device_id,
                            "name": f"{device_name}-默认通道",
                            "status": "ON" if device.get("online", False) else "OFF",
                            "address": f"{device_name}位置",
                            "longitude": 0.0,
                            "latitude": 0.0
                        }]
                    
                    logger.info(f"  设备 {device_id} 有 {len(channels)} 个通道")
                    
                    # 4. 为每个通道创建摄像头
                    for channel in channels:
                        channel_id = (channel.get("channelId") or 
                                    channel.get("id") or 
                                    channel.get("channel_id") or 
                                    device_id)
                        
                        channel_name = (channel.get("name") or 
                                      channel.get("channelName") or 
                                      channel.get("channel_name") or 
                                      f"通道-{channel_id}")
                        
                        # 检查是否已经有对应的摄像头
                        existing_camera = camera_service.db.get_camera_by_wvp_device(device_id, channel_id)
                        if existing_camera:
                            logger.info(f"    ⏭️ 设备 {device_id} 通道 {channel_id} 已有对应摄像头，跳过")
                            skipped_count += 1
                            continue
                        
                        # 创建摄像头数据
                        camera_data = {
                            'name': f"{device_name}-{channel_name}",
                            'wvp_device_id': device_id,
                            'wvp_channel_id': channel_id,
                            'location': channel.get("address", f"{device_name}位置"),
                            'longitude': float(channel.get("longitude", 0.0)),
                            'latitude': float(channel.get("latitude", 0.0)),
                            'description': f"从WVP Java后端设备 {device_name}({device_id}) 通道 {channel_id} 转换",
                            'ai_enabled': True,
                            'status': 'online' if channel.get("status") == "ON" else 'offline',
                            'rtsp_url': f"rtsp://{device.get('ip', '192.168.1.100')}:554/h264/ch{channel_id}/main/av_stream",
                            'processing_fps': 3,
                            'priority_level': 5
                        }
                        
                        try:
                            camera_id = await camera_service.create_camera(camera_data)
                            if camera_id:
                                converted_count += 1
                                logger.info(f"    ✅ 成功转换通道 {channel_id} 为摄像头 {camera_id}")
                            else:
                                logger.error(f"    ❌ 转换通道 {channel_id} 失败: 未返回摄像头ID")
                                error_count += 1
                        except Exception as e:
                            logger.error(f"    ❌ 转换通道 {channel_id} 失败: {e}")
                            error_count += 1
                            continue
                
                except Exception as e:
                    logger.error(f"  ❌ 处理设备 {device_id} 失败: {e}")
                    error_count += 1
                    continue
        
        # 5. 统计结果
        logger.info("🎉 WVP设备转换完成!")
        logger.info(f"  总设备数: {len(devices)}")
        logger.info(f"  新建摄像头: {converted_count}")
        logger.info(f"  跳过摄像头: {skipped_count}")
        logger.info(f"  错误数量: {error_count}")
        
        # 6. 验证结果
        try:
            total_cameras = camera_service.db.execute_query("SELECT COUNT(*) as count FROM cameras")[0]['count']
            wvp_cameras = camera_service.db.execute_query("SELECT COUNT(*) as count FROM cameras WHERE wvp_device_id IS NOT NULL")[0]['count']
            
            logger.info(f"📊 验证结果:")
            logger.info(f"  总摄像头数: {total_cameras}")
            logger.info(f"  WVP摄像头数: {wvp_cameras}")
        except Exception as e:
            logger.warning(f"验证结果时出错: {e}")
            total_cameras = 0
            wvp_cameras = 0
        
        return {
            "success": True,
            "message": "WVP设备转换完成",
            "source": f"Java后端WVP服务 ({connected_url})",
            "total_devices": len(devices),
            "converted_cameras": converted_count,
            "skipped_cameras": skipped_count,
            "error_count": error_count,
            "total_cameras_in_db": total_cameras,
            "wvp_cameras_in_db": wvp_cameras,
            "conversion_time": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"WVP设备转换失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"WVP设备转换失败: {str(e)}")


@router.post("/devices/{device_id}/keepalive")
async def device_keepalive(device_id: str):
    """设备保活"""
    try:
        # 检查设备是否存在
        existing_device = await wvp_device_service.get_device(device_id)
        if not existing_device:
            raise HTTPException(status_code=404, detail="WVP设备不存在")
        
        success = await wvp_device_service.update_keepalive(device_id)
        if not success:
            raise HTTPException(status_code=400, detail="设备保活失败")
        
        return {"message": "设备保活成功", "device_id": device_id}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"设备保活失败: {e}")
        raise HTTPException(status_code=500, detail="设备保活失败")


@router.get("/devices/{device_id}/status")
async def get_device_status(device_id: str):
    """获取设备状态"""
    try:
        status = await wvp_device_service.get_device_status(device_id)
        if not status:
            raise HTTPException(status_code=404, detail="WVP设备不存在")
        return status
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取设备状态失败: {e}")
        raise HTTPException(status_code=500, detail="获取设备状态失败")